<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import tool from '@/utils/tool'
import clientLoginApi from '@/api/auth/client/clientLoginApi'
import UploadForm from '../dev/file/uploadForm.vue'
import tenderApi from '@/api/dev/tenderApi'
const uploadFormRef = ref()

const router = useRouter()
const userInfo = ref<any>({})
const fileName = ref('请上传文件')
// 获取用户信息
const getUserInfo = () => {
	const clientUserInfo = tool.data.get('CLIENT_TOKEN')
	if (clientUserInfo) {
		userInfo.value = clientUserInfo
	}
}


// 定义响应式数据
const imageOSUrls = ref<any>({})
const fileList = JSON.parse(localStorage.getItem('fileList') || '[]')
const fetchimageOSUrls = async () => {
	// 调用API获取数据
	imageOSUrls.value = await tenderApi.getOfficialSeals()
}

// 定义响应式数据
const imageNSUrls = ref<any>({})
const fetchimageNSUrls = async () => {
	// 调用API获取数据
	imageNSUrls.value = await tenderApi.getNameSeals()
}
const toggleNSSelect = (index) => {
	// if (this.selectionMode === 'single') {
	imageNSUrls.value.forEach((img, i) => {
		img.selected = i === index;
	});
	// } else {
	//   imageNSUrls.value[index].selected = !imageNSUrls.value[index].selected;
	// }
	// imageNSUrls.value[index].selected = !imageNSUrls.value[index].selected;
};
// 获取所有选中图片
const selectedNSImages = computed(() => {
	return imageNSUrls.value.filter(img => img.selected);
});
const currentSlideIndex = ref(0)

const carousel = ref(null);
const handlePreview = (index) => {
	currentSlideIndex.value = index
	carousel.value.setActiveItem(index);
}
// 上传标书
const customRequestTender = (data) => {
	// uploadLoading.value = true
	const fileData = new FormData()
	fileData.append('file', data.file)
	fileData.append('dpi', 150)
	fileData.append('quality', 100)
	tenderApi
		.uploadWord(fileData)
		.then((res) => {
			fileList.value = res
			localStorage.setItem('fileList', JSON.stringify(fileList.value))
		})
		.finally(() => {
		})
}
// 上传公章
const customRequestOfficialSeal = (data) => {
	// uploadLoading.value = true
	const fileData = new FormData()
	fileData.append('file', data.file)
	tenderApi
		.uploadOfficialSeal(fileData)
		.then(() => {
			handleSuccess()
		})
		.finally(() => {
		})
}
// 上传名章
const customRequestNameSeal = (data) => {
	const fileData = new FormData()
	fileData.append('file', data.file)
	tenderApi
		.uploadNameSeal(fileData)
		.then(() => {
			handleSuccess()
		})
		.finally(() => {
		})
}
// 退出登录
const handleLogout = async () => {
	try {
		const param = {
			token: tool.data.get('CLIENT_TOKEN')
		}
		await clientLoginApi.clientLogout(param)
		tool.data.remove('CLIENT_TOKEN')
		tool.data.remove('CLIENT_USER_INFO')
		message.success('退出成功')
		router.push('/front/client/login')
	} catch (error) {
		message.error('退出失败')
	}
}

const handleSuccess = () => {
	fetchimageOSUrls() // 在成功回调中调用
	fetchimageNSUrls()
}

// 添加拖拽相关功能
const dragItem = ref(null)
const isDragOver = ref(false)
const dropPosition = ref({ x: 0, y: 0 })
const dragOverIndex = ref(-1) // 记录拖拽经过的幻灯片索引

// 存储已放置的印章
const placedSeals = ref([])

const handleDragStart = (event, item) => {
	dragItem.value = item
	event.dataTransfer.effectAllowed = 'copy'
}

const handleDragOver = (event) => {
	event.preventDefault()
	event.dataTransfer.dropEffect = 'copy'
	isDragOver.value = true
}

const handleDrop = (event, index) => {
	event.preventDefault()
	isDragOver.value = false
	dragOverIndex.value = -1 // 重置拖拽经过的索引

	if (dragItem.value) {
		// 获取释放位置坐标
		const rect = event.currentTarget.getBoundingClientRect()
		dropPosition.value = {
			x: event.clientX - rect.left,
			y: event.clientY - rect.top
		}

		// 处理图片合并逻辑
		mergeImages(index, dragItem.value, dropPosition.value)
	}
	dragItem.value = null
}
const handleSealClick = (index) => {
	console.log('点击了印章', index)
}
const handleDragLeave = (event) => {
	isDragOver.value = false
	dragOverIndex.value = -1
}

// 当拖拽进入某个carousel-item时调用
const handleDragEnter = (index) => {
	dragOverIndex.value = index
}

const mergeImages = (targetIndex, sealImage, position) => {
	// 实现图片合并逻辑
	// 这里应该调用后端API或者使用canvas进行图片合并
	console.log('在位置', position, '合并图片:', sealImage)
	// 将拖放的印章添加到已放置列表中
	placedSeals.value.push({
		id: Date.now(), // 生成唯一ID
		seal: sealImage,
		position: position,
		index: targetIndex // 记录印章应该显示在哪个幻灯片上
	})

	message.success('放置成功')
}

onMounted(() => {
	getUserInfo()
	fetchimageOSUrls()
	fetchimageNSUrls()
})


const headerStyle = {
	textAlign: 'center',
	height: 64,
	paddingInline: 50,
	lineHeight: '64px',
	backgroundColor: '#ffffff'
}
const contentStyle = {
	minHeight: 120,
	lineHeight: '120px',
	color: '#fff'
}
const footerStyle = {
	textAlign: 'center',
	color: '#fff'
}

</script>
<template>
	<a-layout>
		<a-layout-header :style="headerStyle">
			<div style="height: 64px; display: flex; align-items: center; justify-content: space-around">
				<a-avatar :size="50" :src="userInfo.avatar" />
				<span>
					<span style="margin-right: 10px;font-weight: bold;font-size: 20px;">{{ userInfo.name ||
						userInfo.nickname || userInfo.account }}</span>
					<a-button type="primary" danger @click="handleLogout" size="small">退出登录</a-button>
				</span>
			</div>
		</a-layout-header>
		<a-layout-content :style="contentStyle">
			<div class="container-middle">
				<div class="left">
					<div style="background-color: #fff; color: #000; text-align: center; font-size: 28px; height: 60px;
					line-height: 60px; margin-top: 10px;" class="topTitle">标书文件
						<a-upload :show-upload-list="false" :custom-request="customRequestTender">
							<a-button type="primary">
								<upload-outlined></upload-outlined>
								上传
							</a-button>
						</a-upload>
					</div>
					<div class="image-list">
						<img v-for="(item, index) in fileList" :class="currentSlideIndex == (index) ? 'item-index' : ''"
							:key="item.id" :src="item.thumbnail" :preview-src-list="fileList" fit="cover"
							style="width: 100px; height: 100px; margin: 10px;"
							@click="handlePreview(item.index - 1)"></img>
					</div>
				</div>
				<div class="center">
					<el-carousel style="width: 100%; height: 100%;" :autoplay="false" ref="carousel"
						v-model:current-index="currentSlideIndex">
						<el-carousel-item v-for="(item, index) in fileList" :key="index" @dragover="handleDragOver"
							@drop="(event) => handleDrop(event, index)" @dragenter="() => handleDragEnter(index)"
							@dragleave="handleDragLeave"
							:class="{ 'drag-over': isDragOver && dragOverIndex === index }">
							<el-image :src="item.downloadPath + tool.data.get('CLIENT_TOKEN')" />
							<!-- 显示拖拽放置的图片，只在对应的索引显示 -->
							<div v-if="dragItem && isDragOver && dragOverIndex === index" class="dropped-image-preview"
								:style="{ left: dropPosition.x + 'px', top: dropPosition.y + 'px' }">
								<img :src="dragItem.filePath" class="drag-preview-image" />
							</div>
							<!-- 显示已放置的印章，只在对应的索引显示 -->
							<div v-for="placedSeal in placedSeals.filter(seal => seal.index === index)"
								:key="placedSeal.id" class="placed-seal"
								:style="{ left: placedSeal.position.x + 'px', top: placedSeal.position.y + 'px' }">
								<img :src="placedSeal.seal.filePath" class="placed-seal-image"
									@click="handleSealClick(placedSeal)" />
							</div>
						</el-carousel-item>
					</el-carousel>
				</div>
				<div class="right">
					<div style="background-color: #fff; color: #000; text-align: center; font-size: 28px; height: 60px;
					line-height: 60px; margin-top: 10px;" class="topTitle">公章列表
						<a-upload :show-upload-list="false" :custom-request="customRequestOfficialSeal">
							<a-button type="primary">
								<upload-outlined></upload-outlined>
								上传
							</a-button>
						</a-upload>
					</div>
					<div class="image-list">
						<el-image class="nameChapter" v-for="item in imageOSUrls" :key="item.id" :src="item.filePath"
							fit="cover" style="width: 100px; height: 100px; margin: 10px;" draggable="true"
							@dragstart="handleDragStart($event, item)" />
					</div>
					<div style="background-color: #fff; color: #000; text-align: center; font-size: 28px; height: 60px;
					line-height: 60px; margin-top: 10px;" class="topTitle">名章列表
						<a-upload :show-upload-list="false" :custom-request="customRequestNameSeal">
							<a-button type="primary">
								<upload-outlined></upload-outlined>
								上传
							</a-button>
						</a-upload>
					</div>
					<div class="gallery image-list">
						<!-- @click="toggleNSSelect(index)" -->
						<div v-for="(item, index) in imageNSUrls" :key="index" class="gallery-item"
							style="width: 100px; height: 100px;">
							<el-image :src="item.filePath" :class="{ 'selected': item.selected }"
								style="width: 100px; height: 100px;" @dragstart="handleDragStart($event, item)" />
							<!-- <div v-if="item.selected" class="selection-overlay">
								<span class="checkmark">✓</span>
							</div> -->
						</div>
					</div>
				</div>
			</div>

		</a-layout-content>
		<a-layout-footer :style="footerStyle">Footer</a-layout-footer>
	</a-layout>
	<uploadForm ref="uploadFormRef" @successful="handleSuccess" />
</template>

<style scoped lang="less">
:deep(.ant-layout-content) {
	overflow: hidden;
}

* {
	user-select: none;
}

:deep(.el-image) {
	height: 100%;
}

:deep(.el-carousel__item) {
	display: flex;
	justify-content: center;
	align-items: center;
	// position: relative;
}

.item-index {
	border: 1px solid #000;
}

.ant-carousel :deep(.slick-slide) {
	text-align: center;
	background: #364d79;
	// display: flex;
	align-items: center;
	justify-content: center;
}

.ant-carousel :deep(.slick-slide h3) {
	color: #fff;
	flex: 1;
	width: 100%;
	height: 100%;
}

.flexBox {
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;

	.fileImg {
		width: 100%;
		height: 100%;
		object-fit: contain;
		/* 新增: 保证图片完整显示 */
	}
}

.image-list {
	display: flex;
	flex-wrap: wrap;
	overflow-y: auto;
}

.topTitle {
	display: flex;
	justify-content: space-around;
	align-items: center;
}

/* 隐藏垂直滚动条 */
.image-list::-webkit-scrollbar {
	width: 0;
}

/* 隐藏水平滚动条 */
.image-list::-webkit-scrollbar {
	height: 0;
}

.container-middle {
	display: flex;
	height: 100%;
	/* 可根据需要调整高度 */
}

:deep(.slick-slider) {
	height: 100%;
}

:deep(.slick-list) {
	height: 100%;
}

:deep(.slick-track) {
	height: 100%;
}

.left,
.right {
	width: 250px;
	/* 侧边栏固定宽度 */
	display: flex;
	flex-direction: column;
	background: #f0f0f0;
}

:deep(.el-carousel__container) {
	height: 100%;
}

.center {
	flex: 1;
	display: flex;
	/* 中间内容自适应 */
	background: #fff;
	margin: 0 10px;
	width: 100px;
	/* 添加拖拽相关样式 */
	border: 2px dashed transparent;
	transition: border-color 0.3s;
	position: relative;
}

// 修改: 当拖拽到center区域时显示边框效果
.center:has(.drag-over) {
	border-color: #409eff;
	background-color: rgba(64, 158, 255, 0.1);
}

.user-center {
	padding: 10px;
	background: #f0f2f5;

	.header-card {
		margin-bottom: 10px;
	}

	.info-card {
		margin-bottom: 10px;
	}

	.user-header {
		display: flex;

		position: relative;

		.logout-btn {
			position: absolute;
			right: 0;
			top: 50%;
			transform: translateY(-50%);
		}
	}
}

.gallery {
	display: grid;
	// grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
	grid-template-columns: 1fr 1fr;
	gap: 16px;

}

.gallery-item {
	position: relative;
	cursor: pointer;
}

.gallery-item img {
	width: 100%;
	height: 200px;
	object-fit: cover;
	border-radius: 4px;
	transition: all 0.3s ease;
}

.gallery-item img.selected {
	border: 3px solid #42b983;
	transform: scale(0.95);
}

.selection-overlay {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(66, 185, 131, 0.3);
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 4px;
}

.checkmark {
	color: white;
	font-size: 24px;
	font-weight: bold;
}

.dropped-image-preview {
	position: absolute;
	transform: translate(-50%, -50%);
	pointer-events: none;
	z-index: 10;
}

.drag-preview-image {
	max-width: 100px;
	max-height: 100px;
}

.placed-seal {
	position: absolute;
	transform: translate(-50%, -50%);
	z-index: 5;
}

.placed-seal-image {
	max-width: 100px;
	max-height: 100px;
	// 添加: 点击时显示边框
	cursor: pointer;
	border: 2px solid transparent;
	// transition: border-color 0.3s;
}

// 添加: 鼠标悬停时光标变化
.placed-seal-image:hover {
	border-color: #409eff;
	cursor: move;
}

// 添加: 点击时的边框效果
.placed-seal-image:active {
	border-color: #409eff;
}
</style>